#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2015  Data Enlighten Technology (Beijing) Co.,Ltd


import base64
import re
import Lib.Logger.log4py as logging
from mj_parser import common_errors
import sys
import traceback

class PsaParserWeb:
    default_result = {
        "lcdv_base":            '',
        "opb":             '',
        "n_apv_pr":        '',
        "code_centre_prod":  '',
        "date_debut_garantie":       '',
        "date_entree_montage": '',
        "code_famille": '',
        "nre": '',
        "pr": '',
        "organe": ''
    }

    def __init__(self, root_dir):
        self.root_dir = root_dir
        self.logger = logging.get_logger("crawler", "PsaParserWeb")

    def parse(self, file_name):
        b = common_errors.ERR_SUCCESS
        result_list = self.get_default_result()
        try:
            fobj = open(file_name, encoding='utf_8_sig')
            f_buff = fobj.read()
            if f_buff.find('<VEHICULE Existe="O">') < 0:
                # <VEHICULE Existe="N"> 为查询不到VIN
                b = common_errors.ERR_NO_VIN
                return b, result_list

            result_list['lcdv_base'] =self.find_string(f_buff, "LCDV_BASE")[0] if self.find_string(f_buff, 'LCDV_BASE') != '' else ''
            result_list['opb'] = self.find_string(f_buff, 'OPB')[0] if self.find_string(f_buff, 'OPB') != '' else ''
            result_list['n_apv_pr'] = self.find_string(f_buff, 'N_APV_PR')[0] if self.find_string(f_buff, 'N_APV_PR') != '' else ''
            result_list['code_centre_prod'] = self.find_string(f_buff, 'CODE_CENTRE_PROD')[0] if self.find_string(f_buff, 'CODE_CENTRE_PROD') != '' else ''
            result_list['date_debut_garantie'] = self.find_string(f_buff, 'DATE_DEBUT_GARANTIE')[0] if self.find_string(f_buff, 'DATE_DEBUT_GARANTIE') != '' else ''
            result_list['date_entree_montage'] = self.find_string(f_buff, 'DATE_ENTREE_MONTAGE')[0] if self.find_string(f_buff, 'DATE_ENTREE_MONTAGE') != '' else ''
            result_list['code_famille'] = self.find_string(f_buff, 'CODE_FAMILLE')[0] if self.find_string(f_buff, 'CODE_FAMILLE') != '' else ''
            result_list['nre'] = self.find_string(f_buff, 'NRE')[0] if self.find_string(f_buff, 'NRE') != '' else ''
            result_list['pr'] = '|'.join(self.find_string(f_buff, 'ATTRIBUT'))
            result_list['organe'] = '|'.join(self.find_string(f_buff, 'ORGANE'))


            result_list['raw_content'] = base64.b64encode(f_buff.encode('utf-8')).decode('utf-8')

        except Exception as ex:
            try:
                b = common_errors.ERR_UNKNOWN
                exc_info = sys.exc_info()
                self.logger.error(ex)
            finally:
                traceback.print_exception(*exc_info)
                del exc_info
        return b, result_list

    def find_string(self, html,name):
        p=re.compile('<' + name + '>.+?</' + name + '>', re.S)
        div_li =p.findall(html)
        if div_li is not None and len(div_li)>0:
            return [x.replace('<' + name + '>','').replace('</' + name + '>','').replace('\t','').replace('\n','').replace('&nbsp;','').replace('\xa0','') for x in div_li]
            #return div_li[0].replace('<' + name + '>','').replace('</' + name + '>','').replace('\t','').replace('\n','').replace('&nbsp;','').replace('\xa0','')
        else:
            return ''

    def get_pr_info(self, rpos):
        result_list = []
        for pr_item in rpos:
            result_list.append(pr_item["optionCode"])
        return '|'.join(result_list)

    def get_default_result(self):
        return PsaParserWeb.default_result.copy()

if __name__ == '__main__':
    import json
    per = PsaParserWeb('.\\')

    with open('LPAA1CBC0D2002204.json', 'wb') as fo:
        fo.write(json.dumps(per.parse('LPAA1CBC0D2002204.xml'), ensure_ascii=False).encode('utf-8'))
    print(json.dumps(per.parse('LPAA1CBC0D2002204.xml'), ensure_ascii=False).encode('utf-8'))
